
var utils = require("./util.js")

const CMD_READ = "81";
const CMD_WRITTE = "80"; //16进制指令

const parseHex = function(hex){

  if(!hex){
    return;
  }

  hex = hex.toUpperCase();

  //判断读到数据的起始位置 和 数据长度
  if (hex.indexOf("5AA5") == 0) {

    var res = {}

    //得到数据长度 指令+数据+校验
    res.dataLength_hex = hex.substring(4, 6);
    res.dataLenth = parseInt(res.dataLength_hex, 16);

    //得到指令, 指令不需要转换
    res.command_hex = hex.substring(6, 8)

    //得到校验和
    res.verificationSum_hex = hex.substring(hex.length - 2, hex.length)

    //得到数据起始地址,数据地址不需要转换
    res.address_hex = hex.substring(8, 10)

    //得到数据
    res.data_hex = hex.substring(10, hex.length - 2)

    //检查数据长度
    if (res.dataLenth == (1 + 1 + res.data_hex.length / 2 + 1)) {

      res.dataArray = []
      var data_sum = 0;
      //解析数据
      for (var i = 0; i < res.data_hex.length; i += 2){
        var d = res.data_hex[i] + res.data_hex[i + 1];
        res.dataArray.push(d);
        data_sum += parseInt(d, 16);
      }

      //检查校验和
      //分别把每个数据转成10进制
      //var checkSum_ten = parseInt(res.verificationSum_hex, 16)
      var sum = parseInt(res.command_hex, 16) + parseInt(res.address_hex, 16) + data_sum
      var sum_hex = sum.toString(16).toUpperCase();

      if(sum_hex.length > 2){
        sum_hex = sum_hex.substring(sum_hex.length - 2, sum_hex.length)
      }
      if(sum_hex.length < 2){
        sum_hex = "0" + sum_hex;
      }

      res.calSum_hex = sum_hex;

      if (sum_hex == res.verificationSum_hex) {
        //校验成功 返回数据
        return res;
      } else {
        console.log("校验和校验失败! ->" + hex + " 数据:", res);
      }
    } else {
      console.log("数据长度校验失败! ->" + hex  + " 数据:", res);
    }
  } else {
    console.log("invalid hex is :" + hex)
  }
}

/**
 * 生成要发给设备的 值
 * @param dataHex 为16进制数据
 * @return ArrayBuffer
 */
const encodeWritte = function(address, dataArray){
  console.log("要编码的数据是：", dataArray)

  var str = "5AA5";  //帧头
  var dataLength_hex = utils.intTo2Hex(1 + 1 + dataArray.length + 1)
  let command_hex = "80"
  var checksum_ten = parseInt(command_hex, 16) + parseInt(address, 16)

  var dataHex = ""
  for (var i = 0; i < dataArray.length; i++){
    var d = dataArray[i]
    checksum_ten += parseInt(d, 16);
    dataHex += d;
  }

  //checksum_ten 大于80 无论如何都有2位
  var check_sum_hex = checksum_ten.toString(16)
  if(check_sum_hex.length > 2){
    check_sum_hex = check_sum_hex.substring(check_sum_hex.length - 2, check_sum_hex.length)
  }

  str = str + dataLength_hex + command_hex + address + dataHex + check_sum_hex

  return str;
}

module.exports = {
  parseHex: parseHex,
  encodeWritte: encodeWritte
}